package com.xaslsoft.xaslsoft.device.serial.modbus;

/**
 * 异或校验算法
 */
public class XorUtil {
	/**
	 * 异或校验，返回一个字节
	 *
	 * @param hexBytes 待计算校验的字节数组
	 * @return 校验码
	 */
	public static byte Xor2Byte(byte[] hexBytes) {
		int nAll = 0;
		for (int i = 0; i < hexBytes.length; i++) {
			int nTemp = hexBytes[i];
			nAll = nAll ^ nTemp;
		}
		return (byte) nAll;
	}

	/**
	 * 异或校验
	 *
	 * @param hexBytes
	 * @return hexString校验码
	 */
	public static String Xor2Str(byte[] hexBytes) {
		int nAll = 0;
		for (int i = 0; i < hexBytes.length; i++) {
			int nTemp = hexBytes[i];
			nAll = nAll ^ nTemp;
		}
		return byteToHex((byte) nAll);
	}


	public static String byteToHex(byte b) {
		String hex = Integer.toHexString(b & 0xFF);
		if (hex.length() < 2) {
			hex = "0" + hex;
		}
		return hex;
	}


}
